<!-- in-store -->
<template>
    <div class="main-content sp-main store-content">
        <page-header></page-header>
        <el-steps class="sp-step" :active="active" finish-status="success">
            <el-step title="选择归还人员"></el-step>
            <el-step title="清点设备"></el-step>
            <el-step title="入库完成"></el-step>
        </el-steps>
        <div class="in-store-content">
            <div class="top">
                <component
                ref="cmp" 
                :tb2="tb2"
                :buhuan="buhuan" 
                :is="who"></component>
            </div>
            <div class="bottom" >
                <el-button 
                @click="handleNext"
                :loading="submiting"
                :disabled="dis1"
                class="btn">{{btn1val}}</el-button>
                <el-button 
                :disabled="dis2"
                v-if="active != 1"
                @click="handlePrev"
                class="btn">{{btn2val}}</el-button>
            </div>
            
        </div>
    </div>
</template>

<script>
import {
    requestInStore,
    requestReInStore
} from '@/apis'
export default {
    name: 'in-store',
    components: {
        'page-header': () => import('@/components/page-header'), 
        'in-store-select': () => import('@/components/in/in-store-select'), 
        'checkin-devs': () => import('@/components/in/checkin-devs'), 
    },
    data () {
        return {
            active: 1,
            who: 'in-store-select',
            btn1val: '下一步',
            btn2val: '完成',
            dis1: false,
            dis2: true,
            timer: null,
            toolCodeAry: [],
            submiting: false,
            checkFlag: 0,
            buhuan: 1,
            reInId: null,
            reInUser: null,
            rejobTypeName: null,
            reOperateDept: null
        }
    },
    watch: {
        active (newVal, oldVal) {
            if (newVal == 3) return
            let cmps = ['in-store-select', 'checkin-devs']
            this.who = cmps[newVal-1];
            if (newVal == 1) {
                this.btn1val = '下一步';
                this.dis1 = false;
                this.dis2 = true;
            } else if (newVal == 2) {
                if (this.buhuan == 1) {
                    this.btn1val = '入库';
                    this.btn2val = '开始清点';
                } else {
                   this.btn2val = '补还器具';
                   this.btn1val = '补还入库'; 
                }
                
                this.dis1 = true;
                this.dis2 = false;
            }
        },
    },
    computed: {
        tb2 () {
            let tools = JSON.parse(sessionStorage.getItem('devs'));
            let buhuanTools = sessionStorage.getItem('buhuan') ? JSON.parse(sessionStorage.getItem('buhuan')) : [];
            let arr = this.toolCodeAry.map(dev => {
                let _item;
                tools.forEach(tool => {
                    if (tool.toolCode == dev) {
                        _item = tool
                    } 
                
                })
                
                return _item
            })
            let _arr = arr ? arr : [];
            let str = JSON.stringify(_arr);
            sessionStorage.setItem('buhuangongju', str);
            return [...buhuanTools, ...arr]
        },
        url1 () {
            return `https://localhost:8862`
            //return '/local'
        }
    },
    methods: {
        // 下一步
        handleNext () {
            if (this.active == 1) {
                // 校验是否已经选择归还组和归还人员
                let user = sessionStorage.getItem('se-user');
                let group = sessionStorage.getItem('dataId');
                if (user && group) {
                    this.active = 2;
                } else {
                    this.$confirm('请选择归还组和归还人!', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        callback: action => {
                        
                        }
                    });
                }
                
            } 

            // 补还入库
            if (this.btn1val == '入库') {
                this.handleInStore();
            } else if (this.btn1val == '补还入库') {
                this.handleReInStore();
            }
        },
        // 开始清点
        handlePrev () {
            if (this.btn2val == '开始清点' || this.btn2val == '重新清点' || this.btn2val == '补还器具') {
                this.startCheck();
            } else if (this.btn2val == '结束清点') {
                this.stopCheck();
            }
        },   

        // 开始清点
        startCheck () {
            this.$axios.get(this.url1 + '/startCheck').then(res => {
                console.log('清点数据', res);
                this.checkFlag = 1;
                this.btn2val = '结束清点';
                this.timer && window.clearInterval(this.timer);
                this.timer = setInterval(() => {
                    this.recevieData();
                }, 1000)
            })
        },

        // 获取清点数据
        recevieData () {
            this.$axios.get(this.url1 + '/getTagData').then(res => {
                let devs = res.data;
                this.toolCodeAry = Array.from(new Set([...this.toolCodeAry, ...devs]))
            })
        },

        // 结束清点
        stopCheck () {
            
            this.$axios.get(this.url1 + '/stopCheck').then(res => {
                console.log('结束清点', res);
                this.checkFlag = 0;
                this.timer && window.clearInterval(this.timer);
                this.btn2val = '重新清点';
                this.dis1 = false;
            })
        },

        // 入库 请求
        async handleInStore () {
            try {
                this.submiting = true;
                let deptId = window.localStorage.getItem('organizationId');
                let params = {
                    inTools: this.toolCodeAry.map(code => {
                        return {
                            toolCode: code
                        }
                    }),
                    operateDept: deptId,
                    jobTypeName: sessionStorage.getItem('tem'),
                    id: sessionStorage.getItem('dataId'),
                    inUser: sessionStorage.getItem('se-user')
                }
                let res = await requestInStore(params);
                console.log('入库 -- 请求', res);
                let {
                    code,
                    msg
                } = res.data;
                if (code == 200) {
                    this.active = 3;
                    this.$message({
                        type: 'success',
                        message: `入库成功`
                    })
                    this.submiting = false;
                    this.timer1 && clearTimeout(this.timer1);
                    this.timer1 = setTimeout(() => {
                        this.$router.replace('/home').catch({})
                    }, 2000)
                } else if (code == -2) {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.$store.commit('CLEAR_LOGIN');
                    this.$router.push('/login').catch({});
                    this.submiting = false;    
                } else {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.submiting = false;
                }
            } catch(e) {
                console.log('requestInStore',e);
                this.submiting = false;
            }
        },

        // 补还工器具
        async handleReInStore () {
            try {
                this.submiting = true;
                let deptId = window.localStorage.getItem('organizationId');
                // 这里获取新增补录的工器具
                let str = sessionStorage.getItem('buhuangongju') ? sessionStorage.getItem('buhuangongju') : '[]';
                let buhuanArr = JSON.parse(str);
                let id = this.reInId;
                let params;
                if (buhuanArr.length == 0) return;
                params = buhuanArr.map(buhuan => {
                    return {
                        "inoutRecordId": id,
                        "inoutType": 2, // 1出库 2入库 ,
                        "operateType": 1, // 1 自动扫描 2 人工
                        "operateUser": this.reInUser,
                        "toolCode": buhuan.toolCode,
                        "toolName": buhuan.toolName,
                        "toolSpec": buhuan.toolSpec
                    }
                })
                let res = await requestReInStore(id, params);
                console.log('补还工器具 -- 请求', res);
                let {
                    code,
                    msg
                } = res.data;
                if (code == 200) {
                    this.active = 3;
                    this.$message({
                        type: 'success',
                        message: `补还成功`
                    })
                    this.submiting = false;
                    this.timer1 && clearTimeout(this.timer1);
                    this.timer1 = setTimeout(() => {
                        this.$router.replace('/home').catch({})
                    }, 2000)
                } else if (code == -2) {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.$store.commit('CLEAR_LOGIN');
                    this.$router.push('/login').catch({});
                    this.submiting = false;    
                } else {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.submiting = false;
                }
            } catch(e) {
                console.log('requestInStore',e);
                this.submiting = false;
            }
        }
    },
    beforeRouteLeave(to, from, next) {
        if (this.checkFlag != 0) {
            this.stopCheck();
        }
        sessionStorage.removeItem('buhuan');
        this.timer && clearInterval(this.timer);
        this.timer = null;
        next();  
    },
    created () {
        if (Object.keys(this.$route.query) != 0) {
            this.buhuan = 0;
            this.active = 2;
            this.btn2val = '补还器具';
            this.btn1val = '补还入库';
            /* id: "BE6CBB47726346BBB0B4C30F3FD63D21"
            inUser: "刘正"
            jobTypeName: "一级修"
            operateDept: "99" */
            let {
                id,
                inUser,
                jobTypeName,
                operateDept
            } = this.$route.query;
            this.reInId = id;
            this.reInUser = inUser;
            this.rejobTypeName = jobTypeName;
            this.reOperateDept = operateDept;
        }
    }
}
</script>
<style lang='scss'>
.sp-main {
    .sp-step {
        .el-step {
            &:first-child {
                .el-step__head  {
                    .el-step__line {
                        left: 316px!important;
                    }
                }
            }
        }
    }
}
.in-store-content {
    width: 100%;
    height: calc(100% - 146px);
    box-sizing: border-box;

    .top {
        height: calc(100% - 170px);
        padding-top: 32px;
    }

    .bottom {
        height: 80px;
        padding-bottom: 26px;
        padding-top: 32px;

        .btn {
            width: 390px;
            height: 80px;
            background: #2683FF;
            border-radius: 4px;
            float: right;
            margin-right: 42px;
            border-color: #2683FF;
            font-size: 40px;
            color: #FFFFFF;
            letter-spacing: 0;
            font-weight: 400;

            &:nth-child(2) {
                margin-right: 84px;  
            }
        }

        .dis {
            background: #909EB2;
            border-color: #909EB2;
        }

        .aces {
            background: #2683FF;
            border-color: #2683FF;
        }
    }
    
}
</style>